<?
//----------------------------------------------------------------------------------
function get_master_connect(){
	global  $session_db_host, $session_db_user, $session_db_pass;

	if (!$dbh = @mysql_connect($session_db_host, $session_db_user, $session_db_pass))
		return 0;
	return $dbh;
}
//----------------------------------------------------------------------------------
function exit_now(){
	global  $dbh;
	if ($dbh)
		mysql_close($dbh);
	exit;
}
//----------------------------------------------------------------------------------
function kill_old_sessions(){
	global $session_db_name, $dbh,$sessionexp,$userName;
	if($userName){
		$lenght = strlen($userName);
		$patch = " and sess_data like '%s:8:\"userName\";s:$lenght:\"$userName\"%'";
	}
	$SQL = "delete from sessions where tstamp  < date_add(now(), interval - 1 minute) $patch";
	if (!($result1 = @mysql_db_query($session_db_name, $SQL, $dbh)))
		return 0;
	else
		return 1;
}
function kill_session($sid){
	global $session_db_name, $dbh;
	$SQL="delete from sessions where id='$sid'";
	if (!($result = @mysql_db_query($session_db_name, $SQL, $dbh)))	return 0;
	return 1;
}
//----------------------------------------------------------------------------------
function is_blocked($id){
	global $session_db_name, $dbh;
	$SQL = "select blocked from resellers where id='$id'";
	if (($result = @mysql_db_query($session_db_name, $SQL, $dbh)) && ($row=mysql_fetch_array($result)) && ($row[blocked]=="blocked") ) return 1;
	return 0;
}
//----------------------------------------------------------------------------------
function transaction($SQL,$type='0'){
	global $session_db_name, $dbh;

	if(!$dbh) $dbh  = get_master_connect();

	if (!($result = mysql_db_query($session_db_name,"BEGIN", $dbh))) return 0;
	foreach($SQL as $q){
		if($q){
			//echo "$q <br>";
			if (!($result = mysql_db_query($session_db_name, $q, $dbh))){
				//echo mysql_error($result);
				$result = mysql_db_query($session_db_name,"ROLLBACK", $dbh);
				return 0;
			}
			if(!$type){
				if(mysql_affected_rows($dbh) == 0){
					$result = mysql_db_query($session_db_name,"ROLLBACK", $dbh);
					return 0;
				}
			}
		}
	}
	if (!($result = mysql_db_query($session_db_name,"COMMIT", $dbh))) return 0;

	return 1;
}
//---------------------------------------------------------------
function encode_params($params){
	global $template;
	if($template['dir'] == '15') return build_url_query($params);
        $chars = array(
                "=" => "_",
                "+" => "-"
                );
        return strtr(strrev(base64_encode(@gzcompress(serialize($params)))),$chars);
}
//---------------------------------------------------------------
function decode_params($buff=''){
        $result = array();
        foreach ($_GET as $key => $value) {
                if ($value != '') {
                        $result[$key] = $value;
                        continue;
                }

                if(!$buff) $buffer = explode("|||", $key);
                else $buffer = explode("|||",$buff);                                                                                                                                           
                $buffer = $buffer[0];                                                                                                                                                          
                $chars = array(                                                                                                                                                                
                        "_" => "=",                                                                                                                                                            
                        "-" => "+"                                                                                                                                                             
                        );                                                                                                                                                                     
                $array = unserialize(@gzuncompress(base64_decode(strrev(strtr($buffer,$chars)))));
                
                if (is_array($array))
                        $result = array_merge($result, $array);
        }
        return $result;
}
//--------------------------------------------------------------------------------e
function build_url_query($params)
{
	foreach($params as $key=>$value)
		$query .= $key."=".urlencode($value)."&";
	$query = substr($query, 0, -1);
	return $query;
}
//---------------------------------------------------------------------------------
function include_template($file){
	global $webDIR,$baseURL,$sid,$params,$userName,$errorMsg,$statusMsg;
	include("main.html");
}
//---------------------------------------------------------------------------------
function validate($string) {
        return preg_match('/^[^\000-\037\'"`\']+$/', $string)?$string:'';
}

function validate2( $variable, $as_what) {
    switch( $as_what ) {
        case 'email': if( preg_match("/^[a-zA-Z0-9][A-Za-z0-9_\.-]*@([\w\d_-]+\.)+\w{2,5}$/", $variable) ) return $variable;
            return "";
            break;
        case 'domain': if( preg_match("/^([a-z0-9][a-z0-9-]?)*[a-z0-9]\\.([a-z]{2,4})(\\.[a-z]{2,4})?$/", $variable) ) return $variable;
            return "";
            break;
        case 'domain_sld': if( preg_match("/^([a-z0-9][a-z0-9-]*)?$/", $variable) ) return $variable;
            return "";
            break;
        case 'username': if( preg_match("/^[a-zA-Z0-9][a-zA-Z0-9_-]{2,15}$/", $variable) ) return $variable;
            return "";
            break;
        case 'phusername': if( preg_match("/^[a-z][a-z0-9]{2,9}$/", $variable) ) return $variable;
            return "";
            break;
        case 'sub': if( preg_match("/^[a-zA-Z0-9-]{1,20}$/", $variable) ) return $variable;
            return "";
            break;
        case 'password': if( preg_match("/^[a-zA-Z0-9][a-zA-Z0-9_-]{2,9}$/", $variable) ) return $variable;
            return "";
            break;
        case 'path':return $variable;// if( preg_match("/^([.]+)$/i", $variable) ) return $variable;
            return "";
            break;
        case 'country': if( preg_match("/^[a-z]{2,15}$/i", $variable) ) return $variable;
            return "";
            break;
        case 'state': if( preg_match("/^[a-z\s]{2,15}$/i", $variable) ) return $variable;
            return "";
            break;
        case 'address': if( preg_match("/^[\w\d]+/", $variable) ) return pg_escape_string(stripslashes($variable));
            return "";
            break;
        case 'phone': if( preg_match("/^[0-9\+\(\)\.][0-9\s-\(\)\.]+$/", $variable) ) return $variable;
            return "";
            break;
        case 'city': if( preg_match("/^[a-zA-Z][a-zA-Z\s]{1,25}$/", $variable) ) return $variable;
            return "";
            break;
        case 'name': if( preg_match("/^[a-zA-Z\s-]{2,30}$/", $variable) ) return $variable;
            return "";
            break;
        case 'fullname':return $variable;
            break;
        case 'store_name' : if( preg_match("/^[a-zA-Z0-9_\s\-]{4,64}$/", $variable) ) return $variable;
            return "";
            break;
        case 'store_title' :  return $variable;
            return "";
            break;
        case 'language' :  return $variable;
            return "";
            break;
        case 'currency' :  return $variable;
            return "";
            break;
        // Zip check changed to accept codes with 1 char, too. A customer's request
        case 'zip': if( preg_match("/^[\w\d\s\-]{1,31}$/i", $variable) ) return $variable;
            return "";
            break;
        case 'id': if( preg_match("/^[0-9]{1,10}$/", $variable) ) return $variable;
            return "";
            break;
        case 'ip': if( preg_match("/^(\d{1,3}\.){3}\d{1,3}$/", $variable) ) return $variable;
            return "";
            break;
        case 'url':if( preg_match("/^([a-z]{2,5}:\/\/)[a-z0-9-_\.]+\/?[\w-_\.\/]+[?&=\w]*$/", $variable) ) return $variable;
            return "";
            break;
        case 'period':if($variable=='1' or $variable=='3' or $variable=='6' or $variable=='12') return $variable;
            return "";
            break;
        case 'novalidate': if(!$variable || preg_match("/.*/", $variable) ) return $variable;
            return "";
            break;
        case 'text': return $variable;
            break;
        case 'digit': if( preg_match("/^\d*$/", $variable) ) return $variable;
            return "";
            break;
        case 'float': if( preg_match("/^\d*\.\d*$/", $variable) ) return $variable;
            return "";
            break;
        default:  // username ...
            if( preg_match("/^[a-zA-Z][a-zA-Z0-9_-]{3,32}$/", $variable) ) return $variable;
                return "";
            }
            break;
}

//---------------------------------------------------------------------------------
function get_countries($country = '', $vat = FALSE, $only = FALSE){
	$res = '';
	if(!$country) {$country='US';}
	$local_connect = $GLOBALS['master_db'];
	$query = 'SELECT name, iso2, vat FROM countries LEFT JOIN vats ON (country_iso2 = iso2)';
	$local_connect->query($query);
	$result = $local_connect->getAll();
	
	if (is_array($result)){
		foreach($result as $k => $row){
			if (!empty($row['vat'])) {
				$vatString = 'euro="1"';
			}
			else {
				$vatString = 'euro="0"';
			}

			if(!$only or ($only and !empty($row['vat']) == $vat)){
				if($country == $row['iso2']) {
					$res.="<option id='$row[iso2]' value='$row[iso2]' $vatString selected>$row[name]</option>";
				}
				else {
					$res.="<option id='$row[iso2]' value='$row[iso2]' $vatString>$row[name]</option>";
				}
			}
		}
	}
	return $res;
}
//---------------------------------------------------------------------------------
function generate_code($arr,$name="HTTP_POST_VARS"){
	if(is_array($arr)){
		while(list($k,$v)=each($arr)){
			$init.="$k=\$".$name."[".$k."]; <br>\n";
			$validate.="if(!validate($k)){
				\$errorCode=1;
				\$errorMsg=\" invalid  $k \";
				incude_template('openNormal.html');
				exit();
				}
				<br>\n";
			//$validate.="\$".$k."=validate(\$".$k.");<br>";
			$params[]="\$info[$k]";
		}
		$function_calling="if(!function_calling(".implode(",",$params).")";
		$error.="\n<br>	\$error_url=\"\";
				<br><br>\n";
		reset($arr);
	}
	$res="$init<br><br>$validate$function_calling";
	return $res;
}

//----------------------------------------------------------------------------------
function reseller_exists($reseller){
	global $session_db_name, $dbh,$sid;
	$SQL = "SELECT reseller FROM resellers WHERE reseller='$reseller'";
	if ( !($result = @mysql_db_query($session_db_name, $SQL, $dbh))  || !@mysql_num_rows($result) )
			return 0;
	else return 1;
}
//-----------------------------------------------------------------------------
function check_user_pass($user,$password){
/*
	global $session_db_name, $dbh,$sid;
	$SQL = "SELECT reseller FROM resellers WHERE reseller='$user' and password='$password' and blocked='active'";
	if ( !($result = @mysql_db_query($session_db_name, $SQL, $dbh))  || !@mysql_num_rows($result) )
			return 0;
	else return 1;
*/
	
	$local_connect = $GLOBALS['master_db'];
	$query = "SELECT reseller_id FROM resellers WHERE name='$user' and password='$password' and blocked=false";
	$local_connect->query($query);
	if($local_connect->error or $local_connect->numRows() != 1){
		return false;
	}
	return true;
}
//-----------------------------------------------------------------------------
function get_reseller_id($reseller){
	global $session_db_name, $dbh,$sid;
	$SQL = "SELECT id FROM resellers WHERE reseller='$reseller'";
	if ( !($result = @mysql_db_query($session_db_name, $SQL, $dbh))  || !@mysql_num_rows($result) )
			return 0;
	else {
		$row = @mysql_fetch_array($result);
	}
	return $row[id];

}
//-----------------------------------------------------------------------------
function get_reseller_country($id){
	global $session_db_name, $dbh,$sid;
	$SQL = "SELECT country FROM resellers WHERE id='$id'";
	if ( !($result = @mysql_db_query($session_db_name, $SQL, $dbh))  || !@mysql_num_rows($result) )
			return 0;
	else {
		$row = @mysql_fetch_array($result);
	}
	return $row[country];

}
//-----------------------------------------------------------------------------
function change_details($id,$details){
	global $session_db_name, $dbh2,$dbh, $sid;
	$SQL = "UPDATE resellers SET

			firstname='$details[firstname]',
			lastname='$details[lastname]',
			email='$details[email]',
			phone='$details[phone]',
			address1='$details[address1]',
			address2='$details[address2]',
			city='$details[city]',
			state='$details[state]',
			zip='$details[zip]',
			country='$details[country]',
			tax_id='$details[tax_id]',
			newsletter='$details[newsletter]',
      company_name='$details[company_name]',
      vat_num='$details[vat_num]',
      vat_registered='$details[vat_registered]'

			WHERE id = '$id'";

	if ( !($result = @mysql_db_query($session_db_name, $SQL, $dbh)))
        	return 0;
	else{
        	return 1;
	}
}
function change_newsletter_settings($settings,$email,$username){
	global $session_db_name, $dbh,$sid;
	$SQL = "UPDATE resellers SET
			newsletter='$settings'
			WHERE email = '$email' and reseller='$username'";
	if ( !($result = mysql_db_query($session_db_name, $SQL, $dbh)))
			return 0;
	else{
		return 1;
	}
}
//-----------------------------------------------------------------------------
function change_bank_details($id,$details){
	global $session_db_name, $dbh,$sid;
	$SQL = "UPDATE resellers SET
			swift_code='$details[swift_code]',
			bank_name='$details[bank_name]',
			bank_address='$details[bank_address]',
			account_number='$details[account_number]',
			routing_number='$details[routing_number]',
			account_holder='$details[account_holder]',";
	if($details[payment_method])$SQL .= "payment_method='$details[payment_method]',";
	if($details[current_release_level])$SQL .= "current_release_level='$details[current_release_level]',";
	$SQL .= "paypal_email='$details[paypal_email]'
			WHERE id = '$id'";
	if ( !($result = @mysql_db_query($session_db_name, $SQL, $dbh))){
			return 0;
	}else {
		change_bank_details_rp2($id,$details);
		return 1;
	}
}
//-----------------------------------------------------------------------------nd4wd change_bank_details rp2 replication
function change_bank_details_rp2($reseller_id,$details){
	foreach($details as $k=>$v){
		if(trim($v)){
			if($k=='current_release_level'){
				$params[]="release_level='".pg_escape_string($v)."'";
			}else{
				$params[]="$k='$v'";
			}
		}
	}
        $SQL = "UPDATE resellers SET ".implode(',',$params)." WHERE reseller_id=$reseller_id";
        $tmp = trim(implode(',',$params));
        if(!empty($tmp)){
                $GLOBALS['master_db']->query($SQL);
                if($GLOBALS['master_db']->error){
                        mail('nd4wd@bastun.net','change_bank_details_rp2',$SQL);
                }
                $GLOBALS['master_db']->free();
        }
}
//-----------------------------------------------------------------------------nd4wd change_bank_details rp2 replication
function change_password($id,$password){
	global $session_db_name, $dbh,$sid;
	$SQL = "UPDATE resellers SET password='$password' WHERE id='$id'";
	if ( !($result = @mysql_db_query($session_db_name, $SQL, $dbh)))
			return 0;
	else return 1;
}

function get_reseller_password($user,$email){
	global $session_db_name, $dbh;
	$SQL="select password from resellers where reseller='$user' and email='$email'";
	if (!($result = mysql_db_query($session_db_name, $SQL, $dbh))) return 0;
	$row =mysql_fetch_assoc($result);
	return $row[password];
}

//-----------------------------------------------------------------------------
function reseller_has_plan($id,$plan){
	global $session_db_name, $dbh,$sid;
	$SQL = "SELECT plan FROM reseller_plans WHERE id='$id' and plan='$plan'";
	if ( !($result = @mysql_db_query($session_db_name, $SQL, $dbh))  || !@mysql_num_rows($result) )
			return 0;
	else return 1;
}
//-----------------------------------------------------------------------------
function change_plan_settings($id,$settings){
	global $session_db_name, $dbh,$sid;

	if(reseller_has_plan($id,$settings[plan])){
		$SQL = "UPDATE reseller_plans SET
			setup_fee='$settings[setup_fee]',
			domain_price='$settings[domain_price]',
			plan_price='$settings[plan_price]'
			WHERE id='$id' and plan='$settings[plan]'";
	}
	else{
		$SQL = "INSERT INTO  reseller_plans SET
			id='$id',
			plan='$settings[plan]',
			setup_fee='$settings[setup_fee]',
			domain_price='$settings[domain_price]',
			plan_price='$settings[plan_price]',
			has_domain='$settings[has_domain]',
			display_on_index='$settings[display_on_index]'
			";
	}
	if ( !($result = @mysql_db_query($session_db_name, $SQL, $dbh)))
			return 0;
	else return 1;

}
//-----------------------------------------------------------------------------
function list_reseller_plans($id,$type='array'){
	global $session_db_name, $dbh,$sid;
	$SQL = "SELECT
		rp.setup_fee,
		rp.domain_price,
		rp.plan_price,
		rp.has_domain,
		rp.display_on_index,
		rp.description as d,
		rp.offering,
		p.plan,
		p.description,
		p.setup_fee_max,
		p.plan_min_price,
		p.plan_real_price,
		p.plan_max_price,
		p.domain_min_price,
		p.domain_real_price,
		p.domain_max_price
		FROM  plans p
		LEFT JOIN reseller_plans rp on p.plan=rp.plan and  rp.id='$id'";
	if ( !($result = @mysql_db_query($session_db_name, $SQL, $dbh)))
			return 0;
	while ($row = @mysql_fetch_assoc($result)) {
		switch($type){
			case "array":
				$list[] = $row;
			break;
		}
	}
	return $list;
}
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!1
//-----------------------------------------------------------------------------
function list_details($id,$type){
	global $session_db_name, $dbh,$sid;
	$SQL = "SELECT
				id,
				reseller,
				password,
				firstname,
				lastname,
				company,
				email,
				phone,
				address1,
				address2,
				city,
				state,
				zip,
				country,
				tax_id,
				newsletter,
        company_name,
        vat_num,
        vat_registered
			FROM resellers
			WHERE id='$id'";
	if ( !($result = @mysql_db_query($session_db_name, $SQL, $dbh)))
			return 0;
	while ($row = @mysql_fetch_array($result)) {
		switch($type){
			case "table":
				$list .= "";
			break;
			case "array":
				$list[] = $row;
			break;
		}
	}
	return $list;

}
//-----------------------------------------------------------------------------
function list_bank_details($id,$type){
	global $session_db_name, $dbh,$sid;
	$SQL = "SELECT
				swift_code,
				bank_name,
				bank_address,
				account_number,
				routing_number,
				account_holder,
				payment_method,
				paypal_email,
				current_release_level
			FROM resellers
			WHERE id='$id'";
	if ( !($result = @mysql_db_query($session_db_name, $SQL, $dbh)))
			return 0;
	while ($row = @mysql_fetch_array($result)) {
		switch($type){
			case "table":
				$list .= "";
			break;
			case "array":
				$list[] = $row;
			break;
		}
	}
	return $list;

}
//-----------------------------------------------------------------------------
function list_payment_history($id,$type,$details){ // ??
        global $session_db_name, $dbh,$sid,$baseURL;

	if(in_array($_SERVER[REMOTE_ADDR],array('83.228.120.103')))
		$string = '2005-07-01 00:00:00';
	else
		$string = 'now()';

        switch($type){
                case "totals":
			$SQL = "select date_format(date,'%Y-%m') as sdate,PERIOD_DIFF(date_format(now(),'%Y%m'),date_format(date,'%Y%m')) as periods from resellers where id='$id' order by date desc";
                        if ( !($result = @mysql_db_query($session_db_name, $SQL, $dbh)))
                                        return 0;
                        $row = @mysql_fetch_array($result);
                        $signup_date = $row[sdate];
                        $periods_count = $row[periods];
                        for($i=$periods_count;$i>=0;$i--){
                        	$bdate = explode("-",$row[sdate]);
                        	$bdate = date("Y-m",mktime(0,0,0,$bdate[1]+$i,1,$bdate[0]));
                        	$hash[$bdate]="";
                        }
			$SQL="	select
						date_format(date,'%Y-%m') as date,
						date_format(payment_date,'%Y-%m-%d') as payment_date,
						(sum(price)-sum(real_price)) as sum
				from sales
				where
						state = 'normal' and
						id='$id'
						group by date_format(date,'%Y-%m') , date_format(payment_date,'%Y-%m-%d')
				order by date;";
                        if ( !($result = @mysql_db_query($session_db_name, $SQL, $dbh)))
                                        return 0;
                        while ($row = @mysql_fetch_array($result)) {
                        		$hash[$row[date]][sum] = $row[sum];
                        		$hash[$row[date]][pdt] = $row[payment_date];
					if(!$hash[$row[date]][pdt]) $hash[$row[date]][pdt]='Not Paid';
                        }						
                        $SQL = "
				select
				date_format(date,'%Y-%m') as date,
				date_format(ref_payment_date,'%Y-%m-%d') as payment_date,
				sum(real_price)*0.1 as sum
				FROM reseller_links left join sales on (child_id=id and link_type='affiliate')
				where
				type='plan' and
				state = 'normal' and
				parent_id='$id'
				group by date_format(date,'%Y-%m');";							
			if ( !($result = @mysql_db_query($session_db_name, $SQL, $dbh)))
                               return 0;
                        while ($row = @mysql_fetch_array($result)) {				
                                $hash[$row[date]][sum] += $row[sum];
                                $hash[$row[date]][pdt] = $row[payment_date];
				if(!$hash[$row[date]][pdt]) $hash[$row[date]][pdt]='Not Paid';
                        }

			 while(list($date,$h) = each($hash)){
			 	 if(!$h[sum]) $h[sum] = 0;
			 	 if(!$h[pdt] || $h[pdt]=='Not Paid'){
			 	 	if(strtotime($date."-01") < date("U",mktime(0,0,1,date("m")-2,date("d"),date("Y")))){
			 	 		$totals[payable]+= $h[sum];
			 	 		if(!$totals[max_date]) $totals[max_date] = $date;
			 	 	}
			 	 	$totals[total]+= $h[sum];
			 	 	if(!$payed_flag) $totals[min_date] = $date;
			 	 }
				else $payed_flag = true;
			 }
			 setlocale(LC_MONETARY, 'en_US');
			 $totals[total] = money_format("%n",$totals[total]);
			 $totals[payable] = money_format("%n",$totals[payable]);
			 if(!$totals[max_date]) $totals[max_date] = date("Y-m");
			 if(!$totals[min_date]) $totals[min_date] = date("Y-m");
			 return $totals;
                break;        
                case "period":
			$SQL = "select date_format(date,'%Y-%m') as sdate,PERIOD_DIFF(date_format('2005-07-01 00:00:00','%Y%m'),date_format(date,'%Y%m')) as periods from resellers where id='$id' order by date desc";
                        if ( !($result = @mysql_db_query($session_db_name, $SQL, $dbh)))
                                        return 0;
                        $row = @mysql_fetch_array($result);
                        $signup_date = $row[sdate];
                        $periods_count = $row[periods];
                        for($i=$periods_count;$i>=0;$i--){
                        	$bdate = explode("-",$row[sdate]);
                        	$bdate = date("Y-m",mktime(0,0,0,$bdate[1]+$i,1,$bdate[0]));
                        	$hash[$bdate]="";
                        }

			$SQL="	select
						date_format(date,'%Y-%m') as date,
						date_format(payment_date,'%Y-%m-%d') as payment_date,
						(sum(price)-sum(real_price)) as sum
				from sales
				where
						state = 'normal' and
						id='$id'
						group by date_format(date,'%Y-%m') , date_format(payment_date,'%Y-%m-%d')
				order by date;
";
			echo "<!--";
			//echo $SQL;
			echo "-->";
                        if ( !($result = @mysql_db_query($session_db_name, $SQL, $dbh)))
                                        return 0;
                        while ($row = @mysql_fetch_array($result)) {
                        	if(in_array($row[date],array_keys($hash))){
	                		$hash[$row[date]][sum] = $row[sum];
        	        		$hash[$row[date]][pdt] = $row[payment_date];
					if(!$hash[$row[date]][pdt]) $hash[$row[date]][pdt]='Not Paid';
				}
                        }

//!!!!!!!!!!!!1
// abe Stoyane tva tuka za kakvo e ? i kato promenqsh neshto slagai po edin comment 4e stava nqkakva ludnica !!!!!!
//!!!!!!!!!!
						
                        $SQL = "
				select
				date_format(date,'%Y-%m') as date,
				date_format(ref_payment_date,'%Y-%m-%d') as payment_date,
				sum(real_price)*0.1 as sum
				FROM reseller_links left join sales on (child_id=id and link_type='affiliate')
				where
				type='plan' and
				state = 'normal' and
				parent_id='$id'
				group by date_format(date,'%Y-%m');";							
			if ( !($result = @mysql_db_query($session_db_name, $SQL, $dbh)))
                               return 0;
                        while ($row = @mysql_fetch_array($result)) {
				if(in_array($row[date],array_keys($hash))){
	                                $hash[$row[date]][sum] += $row[sum];
        	                        $hash[$row[date]][pdt] = $row[payment_date];
					if(!$hash[$row[date]][pdt]) $hash[$row[date]][pdt]='Not Paid';
				}
                        }

                        $params[sid]=$sid;
                        $params[action]='payment_details';
                        while(list($date,$h) = each($hash)){
                                if(!$h[sum]) $h[sum] = 0;
                                if(!$h[pdt]){
                                        $h[pdt] = "&nbsp;";
					$params[date] == '';
				}else if($h[pdt]=='Not Paid'){
					$params[date] == '';
				}else $params[date]=$h[pdt];

                                $params[period_date]=$date;
                                $link = $baseURL . $webDIR . '//?' . encode_params($params);
                                $list .= "<tr>
                                                        <td style='padding-left:20px;'>".date('F Y',(strtotime($date.'-01')))."</td>
                                                        <td align=right>\$".number_format($h[sum],2,'.',',')."</td>
                                                        <td align=right>".(($h[pdt]!='&nbsp;' and $h[pdt]!='Not Paid') ? date('m/d/Y',strtotime($h[pdt])) : $h[pdt])."</td>".
                                                        "<td align=center><a href='$link'>details</a></td>
                                                </tr>";
                        }
                        return $list;
                break;
                case "unpayed_period":
                        $SQL = "select
                       		date_format(date,'%Y-%m') as date,
                                (sum(price)-sum(real_price)) as sum
                                from sales
                                where
                                (payed is NULL or payed='false') and
                                state = 'normal' and
                                id='$id'
                                group by date_format(date,'%Y-%m')";
                        if ( !($result = @mysql_db_query($session_db_name, $SQL, $dbh)))
                                        return 0;
                        while ($row = @mysql_fetch_array($result)) {
                        		$hash[$row[date]][date] = $row[date];
                        		$hash[$row[date]][sum] = $row[sum];
                        }
			
                        $SQL = "select
							date_format(date,'%Y-%m') as date,
							date_format(payment_date,'%Y-%m-%d') as payment_date,
							sum(real_price)*0.1 as sum
							FROM reseller_links left join sales on (child_id=id and link_type='affiliate')
							where
							(payed_affiliate is NULL or payed_affiliate='false') and
							type='plan' and 
							state = 'normal' and
							parent_id='$id'
							group by date_format(date,'%Y-%m');";
						if ( !($result = @mysql_db_query($session_db_name, $SQL, $dbh)))
                                        return 0;
                        while ($row = @mysql_fetch_array($result)) {
                                $hash[$row[date]][date] = $row[date];
                                $hash[$row[date]][sum] +=$row[sum];
                        }
                        if(is_array($hash)){
				foreach($hash as $h){
                                	$list .= "<tr>
                                                        <td>".$h[date]."</td>
                                                        <td>\$".$h[sum]."</td>
                                                        <td>Unpayed</td>
                                                </tr>";
	                        }
			}
                        return $list;
		break;
                case "details_normal":
                        if(is_array($details)){
                                $SQL = "SELECT
						type,
						count(type) as count,
						sum(price) as price,
						sum(real_price) as real_price,
						(sum(price)-sum(real_price)) as profit
						FROM sales
						WHERE
						id='$id' and
						state!='refund' and
						date >= '$details[start]' and
						date <= DATE_ADD('$details[end]', INTERVAL 1 DAY)
						group by type";
//echo "<!--- ### $SQL --->";
                                if ( !($result = @mysql_db_query($session_db_name, $SQL, $dbh)))
                                                return 0;
                                while ($row = @mysql_fetch_array($result)) {
                                	$list[$row[type]] = $row;
                                }
                                return $list;
                        }
                        return 0;
                break;
                case "details_refund":
                        if(is_array($details)){
                                $SQL = "SELECT
                                                type,
                                                count(type) as count,
                                                sum(price) as price,
                                                sum(real_price) as real_price,
                                                (sum(price)-sum(real_price)) as profit
                                                FROM sales
                                                WHERE
                                                id='$id' and
                                                state='refund' and
                                                date >= '$details[start]' and
                                                date <= '$details[end]'
                                                group by type";
                                
				if ( !($result = @mysql_db_query($session_db_name, $SQL, $dbh)))
                                                return 0;
                                while ($row = @mysql_fetch_array($result)) {
                                        $list[$row[type]] = $row;
                                }
                                return $list;
                        }
                        return 0;
                break;
        }

}
//-----------------------------------------------------------------------------
function get_signup_date($id){
        global $session_db_name, $dbh,$sid;
        		$SQL = "select date_format(date,'%Y-%m-%d') as sdate from resellers  where id='$id'";
                        if ( !($result = @mysql_db_query($session_db_name, $SQL, $dbh)))
                                        return 0;
                        $row = @mysql_fetch_array($result);
                        $signup_date = $row[sdate];
         if($signup_date) return $signup_date;
         else return '2000-01-01';
}

//-----------------------------------------------------------------------------
function list_refunds($id,$type){
	global $session_db_name, $dbh,$sid;
	$SQL = "SELECT
				id
				client
				type
				price
				real_price
				date
				payed
				payment_date
				state
				log_id
			FROM sales
			WHERE id='$id' and state='refund'";
	if ( !($result = @mysql_db_query($session_db_name, $SQL, $dbh)))
			return 0;
	while ($row = @mysql_fetch_array($result)) {
		switch($type){
			case "table":
				$list .= "";
			break;
		}
	}
	return $list;
}
//-----------------------------------------------------------------------------
function list_plan_details($plan,$type){
	global $session_db_name, $dbh,$sid;
	$SQL = "SELECT
				plan,
				description,
				alias,
				setup_fee_max,
				plan_min_price,
				plan_real_price,
				plan_max_price,
				domain_min_price,
				domain_real_price,
				domain_max_price
			FROM plans
			WHERE plan='$plan'";
	if ( !($result = @mysql_db_query($session_db_name, $SQL, $dbh)))
			return 0;
	while ($row = @mysql_fetch_array($result)) {
		switch($type){
			case "table":
				$list .= "";
			break;
			case "array":
				$list[] = $row;
			break;
		}
	}
	return $list;

}
//-----------------------------------------------------------------------------
function get_plan_settings($id){
	global $session_db_name, $dbh,$sid;
/*
	$SQL="select plan from plans";
	
	if ( !($result = @mysql_db_query($session_db_name, $SQL, $dbh))) return 0;
	while($row=mysql_fetch_array($result)) $plans["$row[plan]"]["plan"]=$row["plan"];
*/
	$SQL="select plan,has_domain,display_on_index,setup_fee,domain_price,plan_price,offering from reseller_plans  where id='$id'";
	
	if ( !($result = @mysql_db_query($session_db_name, $SQL, $dbh))) return 0;
	$cc=0;
	while($row=mysql_fetch_array($result)){
		$plans["$row[plan]"]["plan"]=$row["plan"];
		$plans["$row[plan]"]["offering"]=$row["offering"];
		$plans["$row[plan]"]["display_on_index"]=$row["display_on_index"];
		$plans["$row[plan]"]["has_domain"]=$row["has_domain"];
		$plans["$row[plan]"]["domain_price"]=$row["domain_price"];
		$plans["$row[plan]"]["plan_price"]=$row["plan_price"];
		$plans["$row[plan]"]["setup_fee"]=$row["setup_fee"];
	}
	return $plans;
}
//-----------------------------------------------------------------------------
function set_plan_settings($id,$plans,$has_domain,$has_domain_inplan){
	global $session_db_name, $dbh,$sid;
	
	foreach($plans as $p){
		if($p[offering]) $update=" offering='true' ";else $update=" offering='false' ";
		if($p[display_on_index]) $update.=", display_on_index='true' ";else $update.=", display_on_index='false' ";
		$SQL[]="update reseller_plans set $update  where id='$id' and plan='$p[plan]'";
	}
	if($has_domain && !$has_domain_inplan){
		$SQL[]="update reseller_plans set has_domain='true' where id='$id'";
	}else if($has_domain && $has_domain_inplan) {
		$SQL[]="update reseller_plans set has_domain='inplan' where id='$id'";
	}else $SQL[]="update reseller_plans set has_domain='false' where id='$id'";
	return transaction($SQL,1);
}
//-----------------------------------------------------------------------------
function set_minimum_domain_price($id){
	global $session_db_name, $dbh,$sid;
	$SQL="select domain_min_price from plans limit 1";
	if ( !($result = @mysql_db_query($session_db_name, $SQL, $dbh))) return 0;
	$row=mysql_fetch_array($result);
	$SQL="update reseller_plans set domain_price='$row[domain_min_price]' where id='$id';";
	return @mysql_db_query($session_db_name, $SQL, $dbh);

}
//-----------------------------------------------------------------------------
function set_default_description($id,$plan){
        global $session_db_name, $dbh,$sid;
	$data = "0|1|2|3|4|5|6|7|8|9|10|11|12|13";
	$SQL = "update reseller_plans set description='$data' where id='$id' and plan='$plan'";
	if ( !($result = @mysql_db_query($session_db_name, $SQL, $dbh))) return 0;
	return 1;
}
//-----------------------------------------------------------------------------
function set_default_settings($id){
	global $session_db_name, $dbh,$sid,$userName;	
	$SQL = "select plan,domain_min_price,plan_min_price  from plans";
	if ( !($result = @mysql_db_query($session_db_name, $SQL, $dbh))) return 0;
	$SQL = array();
	while($row = @mysql_fetch_assoc($result)){
		$SQL[] = "INSERT INTO reseller_plans values('$id','$row[plan]',0,'$row[domain_min_price]','$row[plan_min_price]','true','true',NULL,'true','0|1|2|3|4|5|6|7|8|9|10|11|12|13')";
	}
	$SQL[]  = "INSERT INTO interface values('$id','15','styles.css','','','','','','','','','','','')";
        $SQL1 = "select disk_space_min_price,domain_min_price,traffic_min_price,ip_min_price,db_min_price,db_space_min_price,ssh_min_price from services";
        if ( !($result = @mysql_db_query($session_db_name, $SQL1, $dbh))) return 0;
        $row = @mysql_fetch_assoc($result);
        $SQL[] = "INSERT INTO reseller_services SET
                disk_space_price = '$row[disk_space_min_price]',
                traffic_price = '$row[traffic_min_price]',
                domain_price = '$row[domain_min_price]',
                ip_price = '$row[ip_min_price]',
                db_price = '$row[db_min_price]',
                db_space_price = '$row[db_space_min_price]',
		ssh_price = '$row[ssh_min_price]',
		registerdomain_price = '10.00',
                id = '$id'";
	$SQL[]="insert into reseller_links (parent_id,child_id,link_type) values('$id','$id','union');";
//	print_r($SQL);
	$ret =  transaction($SQL);
	///--
	// tva e za linkovete :
	//--
	$MenuLinkTitles[] = "Reseller";
	$MenuLinkTitles[] = "Resellers";
	$MenuLinkTitles[] = "Reseller Hosting";
	$MenuLinkTitles[] = "Web Hosting Heseller";
	$MenuLinkTitles[] = "Hosting Reseller";
	$MenuLinkTitles[] = "Resell Web Hosting";

	$MenuLinkSet[menuItem1] = $MenuLinkTitles[array_rand($MenuLinkTitles)];
	$MenuLinkSet[menuItemLink1] = "http://www.resellerspanel.com/?a=$userName|_blank";

	set_interface_settings($id,$MenuLinkSet);
	//---
	return $ret;
}
//-----------------------------------------------------------------------------
function set_reseller_description($id,$plan,$description){
        global $session_db_name, $dbh,$sid;
	$SQL = "update reseller_plans set description='$description' where id='$id' and plan='$plan'";
        if ( !($result = @mysql_db_query($session_db_name, $SQL, $dbh))) return 0;
	return 1;		
}

//-----------------------------------------------------------------------------
function get_interface_settings($id){
	global $session_db_name, $dbh,$sid;
	$SQL = "
		SELECT * 
		FROM interface 
		WHERE id='$id' limit 1;";
	if ( !($result = @mysql_db_query($session_db_name, $SQL, $dbh)))
			return 0;
	$row = @mysql_fetch_assoc($result);
	return $row;
}
//-----------------------------------------------------------------------------
function set_interface_settings($id,$data){
	global $session_db_name, $dbh,$sid;
	// any db connection to rp2
	$db = $GLOBALS['master_db'];
	$dataCopy = $data;
	$queryString = '';
	$dataMenus = array ();
		
	while(list($k,$v) = each($data)){
		$set[] = "$k = '$v'";
	}
	$data = implode(",",$set);
	
	if(empty($data)) {
		return false;
	}
	
	// upadte RP1
	$SQL = "UPDATE interface SET $data WHERE id='$id'";
	$result = @mysql_db_query($session_db_name, $SQL, $dbh);
	
	if (empty($result)) {
		return false;
	}
	
	// sve: RP2 replication
	$search = array ('/^header$/', '/^footer$/', '/^headerData$/', '/^footerData$/');
	$replace = array ('header_type', 'footer_type', 'header_data', 'footer_data');
		
	foreach ($dataCopy as $key => $value) {
		if (!preg_match('/menu/', $key)) {
			$key = preg_replace($search, $replace, $key);
	
			$queryString .= $key." = '$value'";
			
			if ($value != end($dataCopy)) {
				$queryString .= ', ';
			}
		}
		else {
			preg_match('/[0-9]/', $key, $keyMatch);
			preg_match('/Item/', $key, $keyMatchItem);
			preg_match('/Link/', $key, $keyMatchItemLink);
			
			if (!empty($keyMatchItem) && empty($keyMatchItemLink)) {
				$dataMenus[$keyMatch[0]]['title'] = $value;	
			}
			elseif (!empty($keyMatchItemLink)) {
				$value = explode('|', $value);
				$dataMenus[$keyMatch[0]]['url'] = $value[0];
				$dataMenus[$keyMatch[0]]['target'] = $value[1];
			}
			
		}
	}
	
	// if there are any menus to be set - lets do it
	if (!empty($dataMenus)) {
		$queryString = 'menus = \''.base64_encode(serialize($dataMenus)).'\'';
	}
	
	// debug
	// echo $queryString;
	
	$query = <<<echo
UPDATE stores SET $queryString WHERE reseller_id = $id;
echo;
	
	// debug
	// echo $query;
	
	$db->query($query);
	
	if (empty($db->error)) {
		return true;
	}
	else {
		return false;
	}
	
}
//-----------------------------------------------------------------------------
function get_store_name($id){
        global $session_db_name, $dbh,$sid;
        $SQL = "SELECT store_name from resellers where id='$id'";
        if ( !($result = @mysql_db_query($session_db_name, $SQL, $dbh)))
                        return '';
        $row = @mysql_fetch_assoc($result);
        return $row[store_name];
}
//-----------------------------------------------------------------------------
function set_store_name($id,$store_name){
        global $session_db_name, $dbh,$sid;
        $SQL = "UPDATE resellers set store_name= '$store_name' where id='$id'";
        if ( !($result = @mysql_db_query($session_db_name, $SQL, $dbh)))
                        return 0;
	return 1;
}
//-----------------------------------------------------------------------------
function get_sales_mail($id){
        global $session_db_name, $dbh,$sid;
        $SQL = "select r.email,d.domain from resellers r left join domains d using(id) where r.id ='$id'";
        if ( !($result = @mysql_db_query($session_db_name, $SQL, $dbh)))
                        return 0;
	$row = @mysql_fetch_assoc($result);
	if($row[domain]) return  "sales@$row[domain]";
	else return $row[email];
}
//-----------------------------------------------------------------------------
function get_service_prices(){
        global $session_db_name, $dbh,$sid;
        $SQL = "	SELECT 
		disk_space_min_price,
		disk_space_max_price,
		disk_space_real_price,
		domain_min_price,
		domain_max_price,
		domain_real_price,
		traffic_min_price,
		traffic_max_price,
		traffic_real_price,
		ip_min_price,
		ip_max_price,
		ip_real_price,
		db_min_price,
		db_max_price,
		db_real_price,
		db_space_min_price,
		db_space_max_price,
		db_space_real_price,
		ssh_min_price,
		ssh_max_price,
		ssh_real_price,
		registerdomain_min_price,
		registerdomain_max_price,
		registerdomain_real_price

	FROM services limit 1";
        if ( !($result = @mysql_db_query($session_db_name, $SQL, $dbh)))
                        return 0;
        $row = @mysql_fetch_assoc($result);
        return $row;

}
//-----------------------------------------------------------------------------
function set_service_prices($data){
	//global $session_db_name, $dbh,$sid;
	if(is_array($data)){
		while(list($k,$v) = each($data)){
			$s .= " $k = '$v' ,";
		}
		$s = substr($s,0,strlen($s)-1);
	}
	$SQL = "UPDATE services set $s";
        if ( !($result = @mysql_db_query($session_db_name, $SQL, $dbh)))
                        return 0;
	return 1; 
}
//-----------------------------------------------------------------------------
function get_reseller_service_prices($id){
	$resellerId = $GLOBALS['master_db']->escapeStr($id);
	$results = array();
	
	$query = <<<echo
SELECT product_id, name, type, price, wholesale, max_price, min_price FROM products WHERE reseller_id = $resellerId
echo;
	
	$GLOBALS['master_db']->query($query);
	if (empty($GLOBALS['master_db']->error)) {
		while ($row = $GLOBALS['master_db']->getNext()) {
			if ($row['name'] == 'com/net/org/us/info/biz' && $row['type'] != 'registerdomain') {
				continue;	
			}
			$row['price'] = unserialize(base64_decode($row['price']));
			$row['wholesale'] = unserialize(base64_decode($row['wholesale']));
			$row['max_price'] = unserialize(base64_decode($row['max_price']));
			$row['min_price'] = unserialize(base64_decode($row['min_price']));
			$results[$row['name']] = 	$row;
		}
		return $results;
	}
	else {
		return false;
	}
}
//-----------------------------------------------------------------------------
function set_reseller_service_prices($id, $data, $dataCheck){
	$resellerId = $GLOBALS['master_db']->escapeStr($id);
	$query = 'BEGIN;';
		
	foreach ($data as $key => $value) {
		if ($key == $dataCheck['com/net/org/us/info/biz']['product_id']) {
			$price[1]['USD'] = sprintf("%0.2f", $value / 12);
			$price[12]['USD'] = sprintf("%0.2f", $value);
		}
		else {
			$price[1]['USD'] = sprintf("%0.2f", $value);
			$price[12]['USD'] = sprintf("%0.2f", $value*12);
		}
		
		$key = $GLOBALS['master_db']->escapeStr($key);
		$priceInsert = base64_encode(serialize($price));
		
		$query .= <<<ECHO
UPDATE products SET price = '$priceInsert' WHERE reseller_id = $id AND product_id = $key;
ECHO;
	}
	$query .= 'COMMIT;';
	$GLOBALS['master_db']->query($query);
	
	if (empty($GLOBALS['master_db']->error)) {
		return TRUE;
	}
	else {
		return FALSE;
	}
	
	
	/*
	global $session_db_name, $dbh,$sid;
        if(is_array($data)){
                while(list($k,$v) = each($data)){
                        $s .= " $k = '$v' ,";
                }
                $s = substr($s,0,strlen($s)-1);
        }
        $SQL = "update reseller_services set $s where id='$id'";
        if ( !($result = @mysql_db_query($session_db_name, $SQL, $dbh)))
                        return 0;
        return 1;
   */
}
//-----------------------------------------------------------------------------
function list_reseller_clients($id){
        global $session_db_name, $dbh,$sid;
        $SQL = "select client_email,date,client,type,sale_data,state,price from sales where id='$id' order by date  desc";
	if ( !($result = @mysql_db_query($session_db_name, $SQL, $dbh))) return 0;
        while($row = @mysql_fetch_assoc($result)){
		$data[] = $row;
	}
        return $data;
}

// Svilen: added saleId for fetching only a specific sale details
function list_reseller_sales($id, $period, $saleId = NULL){
	global $session_db_name, $dbh,$sid;
	
	if (!empty($saleId)) {
		$saleId = mysql_escape_string($saleId);
		$saleIdPatch = 'AND s.order_number = \''.$saleId.'\'';	
	}

	$SQL = "
		SELECT 	rl.link_type,
						s.client_email,
						DATE_FORMAT(s.date,'%Y-%m-%d') as date,
						s.client,
						s.type,
						s.sale_data,
						s.state,
						s.price,
						s.real_price,
						s.type,
						s.sale_id,
					 (s.real_price)*(rl.link_type='union') as real_price,
					 (s.price)*(rl.link_type='union')+s.real_price*0.1*(rl.link_type='affiliate')*(s.type='plan') as price,
					 	s.payed,
						s.payment_date,
						ref_payed,
						payment_date_affiliate,
						s.expire_date as expire_date
		FROM reseller_links rl LEFT JOIN sales s on(s.id = rl.child_id $saleIdPatch)
		WHERE
			rl.parent_id='$id' AND s.date like '$period%' AND (link_type='union' || link_type='affiliate' and s.type='plan') order by s.date  desc;
	";
  
	if ( !($result = @mysql_db_query($session_db_name, $SQL, $dbh))) {
		return 0;
	}
  
	while($row = @mysql_fetch_assoc($result)) {
		$data[] = $row;
	}

	return $data;
}
function list_reseller_clients_for_renew($id){
        global $session_db_name, $dbh,$sid;
        $SQL = "select client_email,date_format(date,'%d-%m-%Y') as date,client,type,sale_data,state,price from sales where id='$id' and (type='plan' or type='domain' or type='upgrade' or type='renewal' or type='change plan') and state='normal' and client!='' order by sales.date desc";
        if ( !($result = @mysql_db_query($session_db_name, $SQL, $dbh))) return 0;
        while($row = @mysql_fetch_assoc($result)){
		$data[] = $row;
	}
        return $data;
}
//-----------------------------------------------------------------------------


function add_domain_mailbox_email($id,$domain,$pass,$info=''){
//rp2 repl nd4wd
//	add_domain_rp2($id,$domain);
	global $session_db_name, $dbh,$sid;
	include_once('hosting_connect/call.php');
	$func[function_name]="add_domain_mail_mailbox";
	$func[params][domain]=$domain;
	$func[params][pass]=$pass;
	$func[params][info]=$info;
	$res=call_remote_method($func);
	if(!$res) return 0;
	$SQL="insert into domains  set domain='$domain',id='$id'";
	if ( !($result = @mysql_db_query($session_db_name, $SQL, $dbh))) return 0;
	//add_domain_rp2($id,$domain);
	return $res;
}
//-------------------------------------------------------------------------------nd4wd rp2 update
function add_domain_rp2($reseller_id,$domain){
	$SQL = "
		BEGIN;
		INSERT INTO domains VALUES($reseller_id,(SELECT store_id from stores where reseller_id=$reseller_id limit 1),'$domain');
		INSERT INTO dns_cluster.domain_settings (dns_dom_name, mail_server, open_store, enabled, checked, store_id, reseller_id) VALUES('$domain', 'f', 't', 'f', 'f', (SELECT store_id from stores where reseller_id=$reseller_id limit 1), $reseller_id);
		UPDATE dns_cluster.domain_settings SET checked='t' WHERE reseller_id=$reseller_id AND dns_dom_name='$domain';
		COMMIT;
	";

	//$SQL = "INSERT INTO domains VALUES($reseller_id,(SELECT store_id from stores where reseller_id=$reseller_id limit 1),'$domain')";

	$GLOBALS['master_db']->query($SQL);
        if($GLOBALS['master_db']->error){
                mail('errors@bastun.net','add_domain_rp2',$SQL);
		return false;
        }
	$GLOBALS['master_db']->free();
	return true;
}
//-------------------------------------------------------------------------------
function delete_domain_mailbox_email($id,$domain){
        global $session_db_name, $dbh,$sid;

        include_once('hosting_connect/call.php');
        $func[function_name]="delete_domain_mail_mailbox";
        $func[params][domain]=$domain;
        $res=call_remote_method($func);
        if(!$res) return 0;
	if(is_array($domain)){
		$d=implode("' or domain='",$domain);
		$SQL="delete from domains  where id=$id and (domain='$d')";
	}else $SQL="delete from domains  where  domain='$domain' and  id='$id'";
        if ( !($result = @mysql_db_query($session_db_name, $SQL, $dbh))) return 0;
	//delete_domain_rp2($id,$domain);
        return $res;
}
//-------------------------------------------------------------------------------nd4wd rp2 update
function delete_domain_rp2($reseller_id,$domain){
	$SQL = "
		BEGIN;
		DELETE FROM domains WHERE reseller_id=$reseller_id  AND domain='$domain';
		DELETE FROM dns_cluster.domain_settings WHERE reseller_id=$reseller_id AND dns_dom_name='$domain';
		DELETE FROM dns_cluster.domains WHERE reseller_id=$reseller_id AND name='$domain';
		COMMIT;
	";

	//$SQL = "DELETE FROM domains WHERE reseller_id=$reseller_id  AND domain='$domain'";

        $GLOBALS['master_db']->query($SQL);
        if($GLOBALS['master_db']->error){
                mail('errors@bastun.net','delete_domain_rp2',$SQL);
		return false;
        }
        $GLOBALS['master_db']->free();
	return true;
}
//-------------------------------------------------------------------------------
function add_email($domain,$email){
	include_once('hosting_connect/call.php');
	$func[function_name]="add_email";
	$func[params][domain]=$domain;
	$func[params][email]=$email;
	$res=call_remote_method($func);
	return $res;
}
function delete_emails($emails){
	include_once('hosting_connect/call.php');
	$func[function_name]="delete_emails";
	$func[params][mails]=$emails;
	$res=call_remote_method($func);
	return $res;
}
function change_mailbox_pass($pass,$mailbox){
	global $id;
        include_once('hosting_connect/call.php');
        $func[function_name]="change_mailbox_password";
        $func[params][mailbox]=$mailbox;
	$func[params][pass]=$pass;
        $res=call_remote_method($func);
        return $res;
}

function change_all_mailbox_pass($id,$pass){
	
        include_once('hosting_connect/call.php');
        $func[function_name]="change_mailbox_password";
    	$func[params][pass]=$pass;
        $domains =list_reseller_domains($id,'array');
		if(!is_array($domains)) return 1;
		
		foreach($domains as $mailbox){
			$func[params][mailbox]=$mailbox;
    	    $res=call_remote_method($func);
			if(!$res) return 0;
		}
        return 1;
}
function get_reseller_domain($id){
			
	global $session_db_name, $dbh,$sid;
	$SQL = "select domain from domains WHERE id='$id' limit 1;";
        if ( !($result = @mysql_db_query($session_db_name, $SQL, $dbh)))
                        return 0;
        $row = @mysql_fetch_assoc($result);
        return $row[domain];
}
function get_reseller_id_by_domain($domain){

        global $session_db_name, $dbh,$sid;
        $SQL = "select id from domains WHERE domain='$domain' limit 1;";
        if ( !($result = @mysql_db_query($session_db_name, $SQL, $dbh)))
                        return 0;
        $row = @mysql_fetch_assoc($result);
        return $row[id];
}
function get_reseller_name_by_id($id){

        global $session_db_name, $dbh,$sid;
        $SQL = "select reseller from resellers WHERE id='$id' limit 1;";
        if ( !($result = @mysql_db_query($session_db_name, $SQL, $dbh)))
                        return 0;
        $row = @mysql_fetch_assoc($result);
        return $row[reseller];
}

function domain_exist($domain){
	include_once('hosting_connect/call.php');
	$func[function_name]="domain_exist_outer";
	$func[params][domain]=$domain;
	$res=call_remote_method($func);
	return $res;

}
function block_hosting_user($user){
	
        include_once('hosting_connect/call.php');
        $func[function_name]="block_user";
        $func[params]=$user;
        $res=call_remote_method($func);
        return $res;
}
function list_reseller_domains($id,$type='select'){
	global $session_db_name, $dbh,$sid;
	$SQL = "select domain from domains where id='$id';";
	if ( !($result = @mysql_db_query($session_db_name, $SQL, $dbh))) return 0;
	switch($type){
		case "select":
			while($row = @mysql_fetch_assoc($result)){
				$res.="<option value='$row[domain]'>$row[domain]</option>";
			}
			
		break;
		case "array":
			while($row = @mysql_fetch_assoc($result)) $res[]=$row[domain];
		break;
	}
	return $res;

}


function get_reseller_ip_username($domain){
	global $session_db_name, $dbh,$sid;
	$SQL="select r.reseller,r.ip from resellers r left join domains d using(id) where d.domain='$domain';";
	if ( !($result = @mysql_db_query($session_db_name, $SQL, $dbh))) return 0;
	return @mysql_fetch_assoc($result);
}

//---------------------------------------------------------
function get_meta_settings($id){
        global $baseDIR;
        $file = $baseDIR."u/upload/".$id."_meta.cbfl";
        if(is_file($file)){
                $data = file($file);
                foreach($data as $d){
                        if($d){	
				if(substr($d,0,6)=='<title'){
					$buff = explode(">",$d);
					$buff = explode("<",$buff[1]);
					$return[title] = $buff[0];
				}
				else{
	                                $buff = explode("name=\"",$d);
        	                        $name = explode("\" content=\"",$buff[1]);
                	                $content = explode("\">",$name[1]);
                        	        $return[$name[0]] = $content[0];
				}
                        }
                }
        }
        return $return;
}
//---------------------------------------------------------
function set_meta_settings($id,$data){
	global $baseDIR;
        if(!is_array($data)) return 0;
        while(list($k,$v) = each($data)){
		if($k=='title') $ttl = "<title>$v</title>\n";
		else $meta .= "<meta name=\"$k\" content=\"$v\">\n";
        }
	$meta = $ttl.$meta."<meta name=\"revisit-after\" content=\"2 days\">\n<meta name=\"robots\" content=\"index, follow\">\n<meta name=\"language\" content=\"en-us\">\n<meta name=\"distribution\" content=\"Global\">\n<meta name=\"rating\" content=\"General\">\n<meta http-equiv=\"content-type\" content=\"text/html;\">\n";
        $file = $baseDIR."u/upload/".$id."_meta.cbfl";
//        $err = `echo -e '$meta' > $file`;
	
	$fp = fopen($file, "w");
	$err = fputs($fp, $meta);
	fclose($fp);
	if(!$err) {
		//echo $err;
		return 0;
	}
	return 1;

}
//---------------------------------------------------------



function get_refered_sales_stats($id,$details=''){
        global $session_db_name, $dbh,$sid;
		if(is_array($details)){
        $SQL="
				SELECT 
					count(rf.child_id) as count,sum(s.price) as price,sum(s.real_price) as real_price, sum(s.real_price*0.1) profit 
				FROM 	
					resellers r left join 
					reseller_links rf on(r.id=rf.parent_id and rf.link_type='affiliate') left join 
					resellers res on(rf.child_id=res.id) left join 
					sales s on(res.id=s.id and s.type='plan' and s.state='normal') 
				WHERE 
					r.id='$id' and s.id is not NULL and s.date >= '$details[start]' and s.date <= DATE_ADD('$details[end]', INTERVAL 1 DAY)
				GROUP by r.id;
				";	
		}else {
        $SQL="
	
		SELECT 
			count(rf.child_id) as count,sum(s.price) as price,sum(s.real_price) as real_price, sum(s.real_price*0.1) profit 
		FROM 	
			resellers r left join 
			reseller_links rf on(r.id=rf.parent_id and rf.link_type='affiliate') left join 
			resellers res on(rf.child_id=res.id) left join 
			sales s on(res.id=s.id and s.type='plan' and s.state='normal') 
		WHERE 
			r.id='$id' and s.id is not NULL
		GROUP by r.id;
			";
    }  
//echo "<!--$SQL-->" ;
	 if (!($result = mysql_db_query($session_db_name, $SQL, $dbh))) return 0;
	$ref_plan = mysql_fetch_assoc($result);
	if(!$ref_plan[real_price] || $ref_plan[real_price]=='0.00') $ref_plan[count]="0";
        return $ref_plan;
}

function get_refered_sales_stats_detailed($id){
        global $session_db_name, $dbh,$sid;
        $SQL="
		SELECT
			res.reseller ,count(s.id) as count,sum(s.price) as price,sum(s.real_price) as real_price, sum(s.real_price*0.1) profit 
		FROM 	
			resellers r left join 
			reseller_links rf on(r.id=rf.parent_id and rf.link_type='affiliate') left join 
			resellers res on(rf.child_id=res.id) left join 
			sales s on(res.id=s.id and s.type='plan' and s.state='normal') 

		WHERE r.id='$id' group by res.reseller;";
		
	if (!($result = mysql_db_query($session_db_name, $SQL, $dbh))) return 0;
        while($ref_plan= mysql_fetch_assoc($result)){
		if(!$ref_plan[real_price] || $ref_plan[real_price]=='0.00') $ref_plan[count]="0";
		while(list($k,$v)=each($ref_plan)) if(!isset($v)) $ref_plan[$k]='0.00';
		$res.="
		<tr>
		<td> $ref_plan[reseller]</td>
		<td>  $ref_plan[count]</td>
		<td>$ $ref_plan[price]</td>
		<td>$ $ref_plan[real_price]</td>
		<td>$ $ref_plan[profit]</td>
		</tr>";
	}
	return $res;
}
//---------------------------------------------------------
function set_contacts($id,$data){
	if(is_array($data)){
		$SQL[] = "DELETE from contacts where id='$id'";
		while(list($k,$v)= each($data)){			
			if($v[na] && $v[type]) $SQL[] = "INSERT INTO  contacts values('$id','$v[type]','$v[na]','$v[comment]')"; 
		}	
	return transaction($SQL,1);	
	}
	return 1;
}
//---------------------------------------------------------
function get_contacts($id){
	global $session_db_name, $dbh,$sid;
	$SQL = "select type,na,comment from contacts where id='$id'";
        if (!($result = mysql_db_query($session_db_name, $SQL, $dbh))) return 0;
        while($row = @mysql_fetch_assoc($result)){
		switch($row[type]){		
			case "email": $data[0] = $row; break;
			case "icq": $data[1] = $row; break;
			case "phone": $data[2] = $row; break;
			default : $data[3] = $row; break;
		}
        }
        return $data;
}

// sve: Get About Us section on the duoservers 15th template from the PostgreSQL on verdi1
function get_aboutus($db, $resellerId, $section = 'default') {
	$resellerId = (int) $db->escapeStr($resellerId);
	$section = $db->escapeStr($section);
	$aboutUs = array();
	
	$query = <<<echo
SELECT s2.text_title as title, s2.section_text as text FROM stores s1, stores_sections_text s2 WHERE s1.reseller_id = $resellerId AND s1.store_id = s2.store_id AND s2.section = '$section';
echo;
	
	$db->query($query);
	
	while($recordSet = $db->getNext()) {
		$aboutUs[$recordSet['title']] = $recordSet['text'];
	}
	
	if (empty($db->error)) {
		return $aboutUs;
	}
	else {
		return false;	
	}
}

// sve: Update About Us texts
function set_aboutus(&$db, $resellerId, $data, $section = 'default') {
	$resellerId = (int) $db->escapeStr($resellerId);
	$section = $db->escapeStr($section);
	$queryUpdate = '';
	$updatedIds = array();
	
	if (!empty($data)) {
		$query = <<<echo
SELECT s1.stores_sections_text_id, s1.text_title FROM stores_sections_text s1, stores s2 WHERE s2.reseller_id = $resellerId AND s1.section = '$section' AND s1.store_id = s2.store_id;
echo;

		$db->query($query);
		
		if (!empty($db->error)) {
			return false;	
		}
		
		// generate update queries
		while ($recordSet = $db->getNext()) {
			$queryUpdate .= "UPDATE stores_sections_text SET section_text = '".$data[$recordSet['text_title']]."' WHERE stores_sections_text_id = '".$recordSet['stores_sections_text_id']."';";
			$updatedIds[] = $recordSet['text_title'];
		}
		
		// generate insert queries
		foreach ($data as $key => $value) {
			if (!in_array($key, $updatedIds)) {
				$queryUpdate .= "INSERT INTO stores_sections_text (store_id, section, text_title, section_text) VALUES ((SELECT store_id FROM stores WHERE reseller_id = $resellerId), '$section', '$key', '$value');";
			}
		}
		
		// update texts
		$db->query('BEGIN;'.$queryUpdate.'COMMIT;');
		
		if (empty($db->error)) {
			return true;	
		}
		else {
			return false;	
		}
	}
	
	return false;
}

function w9_insert($data){
	global $session_db_name, $dbh,$sid;
	$SQL = "select count(*) as count from w9 where id='$data[id]'";
	if (!($result = mysql_db_query($session_db_name, $SQL, $dbh))) return 0;
	$row = @mysql_fetch_assoc($result);
	if($row[count]>100) return 0;
	$SQL = "insert into w9(". implode(',',array_keys($data)).",date) values ('".implode('\',\'',$data)."' , now())";
	if (!($result = mysql_db_query($session_db_name, $SQL, $dbh))) return 0;
	return 1;

}
//---------------------------------------------------------
//---------------------------------------------------------
function is_me() {
  $ips = array(
  	'88.203.210.65',		// Me
  	'83.228.120.100',		// Me
  	'212.72.214.55',		// Me again -------> Who am I? :)
  	//'212.36.1.54',		// proxy
  	'84.242.134.92', 
	'83.228.120.53',		// Nikolay
  	'83.228.55.157',		// Nikolay
  	//'83.228.120.91',		// Niko
  	// '83.228.120.97',		// Mitia
  	'83.228.49.66',			// Burgas
  	'83.228.120.103',		//nd4wd
    '83.228.120.90',	// Buxter
    '84.21.220.6',		// Sve
    '83.228.120.63',		// Static
    //'83.228.120.68',		// AncientMedia Support
   // '83.228.120.92',		// Milen Burushkin
		'83.228.120.108',		// kalin
    '83.228.120.66',	//abdicator
    '193.125.78.210',	//CJ Udav Ukrainian reseller (MoneyZilla request)
    '10.25.3.117'	//CJ Udav Ukrainian reseller (MoneyZilla request)
  );
  
  if (in_array($_SERVER['REMOTE_ADDR'], $ips)) {
  	return TRUE;
  }
  else {
  	return FALSE;
  }
}
//---------------------------------------------------------


/*
	function paymentProcessorByOrderId($orderId)
  	by Svilen Spasov <svilen@svilen.com>

  params:
  	orderId - string, payment processor order Id
  
  returns:
  	worldpay 				- for WorldPay orderId
    paypal 					- for PayPal orderId
    2co 						- for 2CheckOut orderId
    2co_recurring 	- for 2CheckOut recurring
    clickbank 			- for ClickBank orderId
    wallet 					- for Wallet 
    
  examples:
   
   	$paymentMethod = paymentProcessorByOrderId('2UU27251BD0871929');
   
  examples (orderIds):
   	119486307 - WorldPay
  
    1932942359 - 2Checkout.com
    1928698352 - 2Checkout.com
    64790 - 24056202 - 2Checkout.com - old
    64790 - R52401680 - 2Checkout.com reccuring
    
    2UU27251BD0871929 - PayPal
    4F5670616B596031N - PayPal
    
    ZLVGH8D0 - CLICKBANK
    GRTXK5B0 - CLICKBANK
    
    5W829818LA967132Cref1 - Refund
    
    
    wallet234 - Wallet

*/

function paymentProcessorByOrderId ($orderId = '') {
	$orderId = trim($orderId);
  
  if (!empty($orderId)) {
  	$method = 'unknown';
    $refund = substr_count($orderId, 'ref');
    $wallet = substr_count($orderId, 'wallet');
    
    // If the orderId is being refunded one
    if ($refund > 0) {
    	$orderId = substr($orderId, 0, strpos($orderId, 'ref'));
    }
    
    $length = strlen($orderId);
    $numeric = (bool) is_numeric($orderId);
    $dash = substr_count($orderId, '-');
    $Rletter = substr_count($orderId, 'R');
    
    switch (true) {
    	case ($wallet > 0):
      	// Wallet
      	$method = 'wallet';
      	break;
      case ($dash == 1 && $Rletter == 1):
      	// 2CheckOut recurring
       	$method = '2co_recurring';
        break;
    	case ($dash == 1 && $Rletter != 1):
      	// 2CheckOut
       	$method = '2co';
        break;
      case ($numeric === FALSE && $length == 9 && $Rletter == 1):
      	// 2CheckOut Old
        $method = '2co_recurring';
      	break;
      case ($numeric === TRUE && $length == 8):
      	// 2CheckOut Old
        $method = '2co';
      	break;
      case ($numeric === TRUE && $length == 10):
      	// 2CheckOut
      	$method = '2co';
        break;
      case ($numeric === TRUE && $length == 9):
      	// WorldPay
        $method = 'worldpay';
      	break;
      case ($numeric === FALSE && $length == 17):
       	// PayPal Id
        $method = 'paypal';
        break;
      case ($numeric === FALSE && $length == 8):
      	// ClickBank
      	$method = 'clickbank';
      	break;
    }
    
    
  	return $method;
  
  }
  else {
  	return '';
  }
}

/* 
	~~~ GMT Time Magic v2.1 ~~~~~~~~~~
	
  example time:
  date("l, F jS Y, H:i:s", GMT_Time($Timestamp,1) + 3600 * $Timezone)
  
  example timestamp:
  GMT_Time($Timestamp,(-1)) + 3600 * $Timezone
*/
function GMT_Time($Stamp,$Change) {
   return (($Stamp == 0) ? time() : $Stamp) - $Change * date("Z");
}


/*
 by paz
*/
function print_plan_properties($product_id) {
        global $dbh81;
        //-----------------------------------------------------
                $sql['type'] = "SELECT";
                $sql['params'] = "name,services,wholesale";
                $sql['table'] = "products";
                $sql['where'] = "product_id = '$product_id'";
                $sql['options'] = "";
                $sql['return'] = "struct";
        //------------------------------------------------------
        #exit($result=sql_exec($sql,$dbh81,'assoc'));
        if (!$result=sql_exec($sql,$dbh81,'assoc')) {
                exit("Temporary Error!");
        }
        $name = $result[0]['name'];
        $array = $result[0]['services'];
        $wholesale = $result[0]['wholesale'][12]['USD'];

        $disk_space = $array['disk_space']/1024;
        $traffic = $array['traffic']/1024/1000;
        echo "<TABLE width='300' class='bTable' cellspacing=0>
                <tr>
                        <th colspan=2>$name Plan properties</th>
                </tr>
                <tr>
                        <td>Disk Space</td>
                        <td>$disk_space MB</td>
                </tr>
                <tr>
                        <td>Traffic</td>
                        <td>$traffic GB</td>
                </tr>
                <tr>
                        <td>Domains</td>
                        <td>".$array['domain']."</td>
                </tr>
                <tr>
                        <td>Subdomains</td>
                        <td>".$array['subdomain']."</td>
                </tr>
                <tr>
                        <td>E-mail addresses</td>
                        <td>".$array['mailbox']."</td>
                </tr>
                <tr>
                        <td>E-mail Aliases</td>
                        <td>".$array['aliases']."</td>
                </tr>
                <tr>
                        <td>E-mail Lists</td>
                        <td>".$array['mail_list']."</td>
                </tr>
                <tr>
                        <td>Mysql Databases</td>
                        <td>".$array['sql']."</td>
                </tr>
                <tr>
                        <td>Mysql Quota</td>
                        <td>".$array['sql_quota']." MB</td>
                </tr>
                <tr>
                        <td>SSH</td>
                        <td>";
                        if ($array['ssh'] == 0) {
                                echo 'Off';
                        } else {
                                echo 'On';
                        }
                echo "</td>
                </tr>
                <tr>
                        <td>IP Addresses</td>
                        <td>".$array['ip']."</td>
                </tr>
                <tr>
                        <td>FTP Accounts</td>
                        <td>".$array['ftp']."</td>
                </tr>
                <tr>
                        <td>Cron Jobs</td>
                        <td>".$array['crontab']."</td>
                </tr>
                <tr>
                        <td>Wholesale Price (annual)</td>
                        <td>$".$wholesale." USD</td>
                </tr>
                </table>";
}

/*
 by paz
*/
function print_plan_properties2($product_id) {
        global $dbh81;
        //-----------------------------------------------------
                $sql['type'] = "SELECT";
                $sql['params'] = "name,services,wholesale";
                $sql['table'] = "products";
                $sql['where'] = "product_id = '$product_id'";
                $sql['options'] = "";
                $sql['return'] = "struct";
        //------------------------------------------------------
        #exit($result=sql_exec($sql,$dbh81,'assoc'));
        if (!$result=sql_exec($sql,$dbh81,'assoc')) {
                exit("Temporary Error!");
        }
        $name = $result[0]['name'];
        $array = $result[0]['services'];
        $wholesale = $result[0]['wholesale'][12]['USD'];

        $disk_space = $array['disk_space']/1024;
        $traffic = $array['traffic']/1024/1000;
        echo "<TABLE width='100%' class='bTable' cellspacing=0>
        <tr>
                <th colspan=5>$name Plan properties</th>
        </tr>
        <tr>
                <td width='30%'><b>Disk Space</b></td>
                <td width='15%'>$disk_space MB</td>
                <td width='10'>&nbsp;</td>
                <td width='30%'><b>E-mail addresses</b></td>
                <td width='15%'>".$array['mailbox']."</td>
        </tr>
        <tr>
                <td width='30%'><b>Traffic</b></td>
                <td width='15%'>$traffic GB</td>
                <td width='10'>&nbsp;</td>
                <td><b>E-mail Aliases</b></td>
                <td>".$array['aliases']."</td>
        </tr>
        <tr>
                <td><b>Domains</b></td>
                <td>".$array['domain']."</td>
                <td width='10'>&nbsp;</td>
                <td><b>E-mail Lists</b></td>
                <td>".$array['mail_list']."</td>
        </tr>
        <tr>
                <td><b>Subdomains</b></td>
                <td>".$array['subdomain']."</td>
                <td width='10'>&nbsp;</td>
                <td><b>Cron Jobs</b></td>
                <td>".$array['crontab']."</td>
        </tr>
        <tr>
                <td><b>FTP Accounts</b></td>
                <td>".$array['ftp']."</td>
                <td width='10'>&nbsp;</td>
                <td><b>Site Studio</b></td>
                <td>";
                if ($array['site_studio'] == 0) {
                        echo "Off";
                } else {
                        echo "On";
                }
                echo "</td>
        </tr>
        <tr>
                <td><b>Mysql Databases</b></td>
                <td>".$array['sql']."</td>
                <td width='10'>&nbsp;</td>
                <td><b>IP Addresses</b></td>
                <td>".$array['ip']."</td>
        </tr>
        <tr>
                <td><b>Mysql Quota</b></td>
                <td>".$array['sql_quota']." MB</td>
                <td width='10'>&nbsp;</td>
                <td><b>SSH</b></td>
                <td>";
                if ($array['ssh'] == 0) {
                        echo 'Off';
                } else {
                        echo 'On';
                }
                echo "</td>
        </tr>
        </table>";
}

/*
 by paz
*/
function get_plan_expire_date($client_id) {
        global $dbh81;
        if (empty($client_id)) return FALSE;
        //------------------------------------------------------
        $sql['type'] = "SELECT";
        $sql['params'] = "a.expire_date";
        $sql['table'] = "purchases as a,clients as b, products as c";
        $sql['where'] = "a.client_id=b.client_id and b.client_id='$client_id' and a.product_id=c.product_id and c.type='plan'";
        $sql['options'] = "";
        $sql['return'] = "struct";
        //------------------------------------------------------
        if (!$result=sql_exec($sql,$dbh81,'assoc')) {
                return FALSE;
        } else {
                $expire_date=$result[0][expire_date];
                return $expire_date;
        }
}

// sve: return the full country name by give iso2
function get_country_name ($iso) {
	$iso = mysql_escape_string($iso);
		
	$query = <<<echo
SELECT name FROM countries WHERE iso2 = '$iso';
echo;
	
	$result = @mysql_db_query($GLOBALS['session_db_name'], $query, $GLOBALS['dbh']);
	
	if (empty($result)) {
		return false;
	}
	
	$resultSet = @mysql_fetch_array($result, 1);
	
	return ucwords(strtolower($resultSet['name']));
}

function change_company_mysql ($resellerId, $companyName) {
	$companyName = mysql_escape_string($companyName);
	$resellerId = (int) $resellerId;
	
	$query = <<<echo
UPDATE resellers SET company_name = '$companyName' WHERE id = $resellerId;
echo;
	
	$result = @mysql_db_query($GLOBALS['session_db_name'], $query, $GLOBALS['dbh']);
	
	if (!empty($result)) {
		return true;
	}
	else {
		return false;
	}
}

function change_company_pgsql ($db, $resellerId, $companyName) {
	$companyName = mysql_escape_string($companyName);
	$resellerId = (int) $resellerId;
	
	$query = <<<echo
UPDATE resellers SET company = '$companyName' WHERE reseller_id = $resellerId;
echo;
	
	$db->query($query);
		
	if (empty($db->error)) {
		return true;
	}
	else {
		return false;
	}
}

function createDBHostingObject ($clientUsername) {
	$clientUsername = $GLOBALS['master_db']->escapeStr($clientUsername);
			
	$query = <<<echo
SELECT c.client_id, c.server, s.db_user, s.db_pass, s.db_name FROM clients c, servers s WHERE c.username = '$clientUsername' AND c.server = s.name
echo;
	$GLOBALS['master_db']->query($query);
	$recordSet = $GLOBALS['master_db']->getNext();
	
	$dbPh = anyDB::getLayer('POSTGRESQL', '', 'pgsql');
	$dbPh->connect($recordSet['server'], $recordSet['db_name'], $recordSet['db_user'], $recordSet['db_pass']);
	
	return $dbPh;
}

// Decode query string
function decodeQueryString () {
	if(!empty($_SERVER['QUERY_STRING'])) {
		// decode params
		$params = decode_params();
		
		if(!empty($params)) {
			while(list($key, $value) = each($params)) {
				$GLOBALS[$key] = $value;
			}
		}
	}
}

// returns reseller's password by username and email
function getResellerPasswordRP2 ($username, $email) {
	$username = $GLOBALS['master_db']->escapeStr($username);
	$email = $GLOBALS['master_db']->escapeStr($email);
	
	$query = <<<echo
SELECT password FROM resellers WHERE name = '$username' AND email = '$email'
echo;
	
	$GLOBALS['master_db']->query($query);
	
	if (empty($GLOBALS['master_db']->error)) {
		return $GLOBALS['master_db']->getValue();
	}
	else {
		return false;
	}
}

function fix_empty_remote_forms($reseller_id,$select_type) {
    global $dbh81;
    $qu[] = "insert into interface_settings (reseller_id,interface_type,element_type,color,width,align) 
	VALUES ('$reseller_id','order','border','#000000','1','')";
    $qu[] = "insert into interface_settings (reseller_id,interface_type,element_type,color,width,align) 
	VALUES ('$reseller_id','order','background','#ffffff','','')";
    $qu[] = "insert into interface_settings (reseller_id,interface_type,element_type,color,width,align) 
	VALUES ('$reseller_id','order','font','#000000','','')";
    $qu[] = "insert into interface_settings (reseller_id,interface_type,element_type,color,width,align) 
	VALUES ('$reseller_id','order','error','#000000','','')";
    $qu[] = "insert into interface_settings (reseller_id,interface_type,element_type,color,width,align) 
	VALUES ('$reseller_id','order','terms','#000000','','')";
    $qu[] = "insert into interface_settings (reseller_id,interface_type,element_type,color,width,align) 
	VALUES ('$reseller_id','order','left_col','','40%','right')";
    $qu[] = "insert into interface_settings (reseller_id,interface_type,element_type,color,width,align) 
	VALUES ('$reseller_id','order','right_col','','','left')";
    $qu[] = "insert into interface_settings (reseller_id,interface_type,element_type,color,width,align) 
	VALUES ('$reseller_id','domain','border','#000000','1','')";
    $qu[] = "insert into interface_settings (reseller_id,interface_type,element_type,color,width,align) 
	VALUES ('$reseller_id','domain','background','#ffffff','','')";
    $qu[] = "insert into interface_settings (reseller_id,interface_type,element_type,color,width,align) 
	VALUES ('$reseller_id','domain','font','#000000','','')";
    $qu[] = "insert into interface_settings (reseller_id,interface_type,element_type,color,width,align) 
	VALUES ('$reseller_id','domain','text','#000000','','')";
    $qu[] = "insert into interface_settings (reseller_id,interface_type,element_type,color,width,align) 
	VALUES ('$reseller_id','domain','result','#000000','','')";
    $qu[] = "insert into interface_settings (reseller_id,interface_type,element_type,color,width,align) 
	VALUES ('$reseller_id','domain','links','#000000','','')";
    $qu[] = "insert into interface_settings (reseller_id,interface_type,element_type,color,width,align) 
	VALUES ('$reseller_id','domain','title','#000000','','')";
    $qu[] = "insert into interface_settings (reseller_id,interface_type,element_type,color,width,align) 
	VALUES ('$reseller_id','template','1','c','','')";
    $sql['type'] = "transaction";
    $sql['params'] = $qu;
    $sql['table'] = "";
    $sql['options'] = "";
    $sql['return'] = "";
    if (!$trans_result=sql_exec($sql,$dbh81)) {
	return 0;
    } else {
	//------------------------------------------------------
	$sql['type']='SELECT';
	$sql['params']='*';
	$sql['table']='interface_settings';
	$sql['where']="reseller_id='$reseller_id' and interface_type = '$select_type'";
	$sql['options']='';
	$sql['return']='struct';
	//------------------------------------------------------
	if (!$result = sql_exec($sql,$dbh81,'assoc')) {
	    return 0;
	} else {
	    return $result;
	}
    }
}


function monthly_price ($array) {
	if (!empty($array[1]['USD'])) {
		return sprintf("%0.2f", $array[1]['USD']);
	}
	else {
		return sprintf("%0.2f", $array[12]['USD'] / 12);
	}
}

function yearly_price ($array) {
	if (!empty($array[12]['USD'])) {
		return sprintf("%0.2f", $array[12]['USD']);
	}
	else {
		return sprintf("%0.2f", $array[1]['USD'] * 12);
	}
}

?>
